package com.ndhutu.ee.util.http;

import okhttp3.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * http请求工具类
 * @Author Shane
 **/
public class OKHttpUtil {
    /**
     * post请求
     * @param url
     * @param params    请求参数集合
     * @return
     * @throws IOException
     */
    public static String post(String url, Map<String, String> params) throws IOException{
        OkHttpClient client = new OkHttpClient();
        RequestBody body = setBody(params);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = client.newCall(request);
        return call.execute().body().string();
    }


    /**
     * post请求
     * @Author Shane
     * @Date 2019/8/11 13:07
     * @param params    请求参数集合
     * @param headers   请求头集合
     * @return
     */
    public static String post(String url, Map<String, String> params, Map<String, String> headers) throws IOException{
        OkHttpClient client = new OkHttpClient();
        RequestBody body = setBody(params);

        Request.Builder builder = setHeader(headers);
        Request request = builder
                .url(url)
                .post(body)
                .build();
        Call call = client.newCall(request);
        return call.execute().body().string();
    }


    /**
     * 设置请求参数参数
     * @Author Shane
     * @Date 2019/8/11 13:04
     * @param
     * @return
     */
    private static RequestBody setBody(Map<String, String> params){
        FormBody.Builder builder = new FormBody.Builder();
        for(Map.Entry<String, String> entry : params.entrySet()){
            builder.add(entry.getKey(), entry.getValue());
        }
        return builder.build();
    }

    /**
     * 设置请求头
     * @Author Shane
     * @Date 2019/8/11 13:04
     * @param
     * @return
     */
    private static Request.Builder setHeader(Map<String, String> headers){
        Request.Builder builder = new Request.Builder();
        for(Map.Entry<String, String> entry : headers.entrySet()){
            builder.addHeader(entry.getKey(), entry.getValue());
        }
        return builder;
    }

    /**
     * post json数据
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String post(String url, String json) throws IOException{
        RequestBody body = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), json);
        Request request = new Request.Builder().url(url).post(body).build();
        Call call = new OkHttpClient().newCall(request);
        return call.execute().body().string();
    }

    /**
     * post json数据
     * @Author AppiJ
     * @Date 2020/4/20 15:35
     * @param url
     * @param json
     * @param headers
     * @return
     */
    public static String post(String url, String json, Map<String, String> headers) throws IOException{
        RequestBody body = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), json);
        Request.Builder builder = setHeader(headers);
        Request request = builder.url(url).post(body).build();
        Call call = new OkHttpClient().newCall(request);
        return call.execute().body().string();
    }

    /**
     *get请求
     * @param url
     * @return
     * @throws IOException
     */
    public static String get(String url) throws IOException{
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        return call.execute().body().string();
    }

    /**
     * get请求
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String get(String url, Map<String, String> params) throws IOException{
        StringBuffer buff = new StringBuffer();
        for(Map.Entry<String, String> entry : params.entrySet()){
            buff.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "utf-8")).append("&");
        }
        String s = buff.substring(0, buff.length()-1);

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url+"?"+s)
                .build();
        Call call = client.newCall(request);
        return call.execute().body().string();
    }

    /**
     * 参数排序
     * @param params
     * @return
     * @throws Exception
     */
    public static String sortParam(Map<String, Object> params) throws Exception{
        Set<String> keySets = params.keySet();
        List<String> keys = new ArrayList<String>(keySets);
        Collections.sort(keys);
        StringBuffer buff = new StringBuffer();
        for(String key : keys){
            buff.append(key).append("=").append(URLEncoder.encode(params.get(key)+"", "utf-8")).append("&");
        }
//		System.out.println(buff);
        String str = "";
        if(buff.length() > 0){
            str = buff.substring(0, buff.length()-1);
        }
        return str;
    }

    /**
     * 参数排序
     * @param params
     * @param encode    是否编码
     * @return
     * @throws Exception
     */
    public static String sortParam(Map<String, String> params, Boolean encode) throws Exception{
        Set<String> keySets = params.keySet();
        List<String> keys = new ArrayList<String>(keySets);
        Collections.sort(keys);
        StringBuffer buff = new StringBuffer();
        for(String key : keys){
            String value = null;
            if(encode){
                value = URLEncoder.encode(params.get(key), "utf-8");
            }else{
                value = params.get(key);
            }
            buff.append(key).append("=").append(value).append("&");
        }
//		System.out.println(buff);
        String str = "";
        if(buff.length() > 0){
            str = buff.substring(0, buff.length()-1);
        }
        return str;
    }



    public static void main(String[] args) throws Exception{
        Map<String, Object> params = new HashMap<String, Object>(5);
        params.put("aaa", 1);
        params.put("a1a", 1);
        params.put("1aa", 1);
        params.put("111", 1);
        String str = sortParam(params);
        System.out.println(str);
    }
}
